<?php
/**
 * Create by PhpStorm
 * Member Administrator
 * Date 2019/9/26
 * Time 16:44
 */

namespace app\api\controller\mall;

use think\Db;
use think\Validate;
use think\Cache;
use think\Session;
use think\Request;
use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords;
use app\api\model\User;
use app\api\model\MallDistribution;
use app\api\model\MallOrderFanli;

class Member extends CommonMall
{

    /**
     * 析构
     * Member constructor
     * @param string $tokenaaa
     */
    /*public function __construct($tokenaaa = '')
    {
        parent::__construct();

        // 全局安全过滤
        Request::instance()->filter(['strip_tags', 'htmlspecialchars_decode', 'trim']);

        //"o3or6VZXhEPIIcby4wP9fJeqtvkfZRUm2QvXxbaLwIxNbal+kDmOD7w4qZl7fXI9fYlSa6Wixt0v";

        // 读取会员配置 - 开始
        $config = Db::name('member_config')->where('name', 'switch')->value('text');
        unset($data);   // 销毁变量

        // 会员是否开启 - 开始
        if (!$config || $config == 0) {
            exit(json_encode(['err' => '会员未开放']));
        }

        // 会员是否开启 - 结束
        // 获取登录token
        $token = Session::get('user', 'ffxiangUser') ? Session::get('user', 'ffxiangUser') : rawurldecode(urlencode(urldecode(input('token'))));

        if (!$token) {
            if ($tokenaaa) {
                $token = $tokenaaa;
            } else {
                exit(json_encode(['err' => 'token不正确']));
            }
        }

        // 解密token UID
        $uid = _Dencrypt($token, 'D');

        if (!$uid) {
            echo json_encode(['err' => '会员UID不正确，请重新获取token']);
            exit();
        }
        // 解密成功获取会员信息
        $member = _user($uid);
        // 检测会员限制
        if ($member) {
            switch ($member['hide']) {
                case '0':
                    $recording = _records($member['id'], 'API操作,账户被禁止');
                    if ($recording) {
                        $data = ['err' => '无法登录，原因是账户已被封号'];
                    }
                    exit(json_encode($data));
                case '2':
                    $recording = _records($member['id'], 'API操作,账户正在审核');
                    if ($recording) {
                        $data = ['err' => '账户正在审核，请等待客服处理'];
                    }
                    exit(json_encode($data));
                case '3':
                    $recording = _records($member['id'], 'API操作，账户审核被拒绝');
                    if ($recording) {
                        $data = ['err' => '账户审核被拒绝，拒绝原因：' . $member['hidetent']];
                    }
                    exit(json_encode($data));
            }
        } else {
            echo json_encode(['err' => '会员不存在']);
            exit();
        }
        $this->member = $member;
    }*/

    /**
     * 用户收藏列表
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function favourite()
    {
        $uid = $this->member_relang['id'];

        $page = input('page/d') ? input('page/d') : 1;

        // 开始验证
        $validate = new Validate([
            ['page', 'number|>:0', '分页有误|分页有误'],
        ]);

        $data = [
            'page' => $page,
        ];

        if (!$validate->check($data)) {
            return $this->pass($validate->getError());
        } else {
            try {
                $data = $this->db->name('mall_goods_favourite t1')
                    ->field("t1.id, FROM_UNIXTIME(t1.create_time,'%Y-%m-%d %H:%i') create_time, t2.id goods_id, t2.image, t2.name, t2.price")
                    ->join('mall_goods t2', 't2.id = t1.goods_id')
                    ->where([
                        't1.user_id' => $uid,
                        /*'t1.delete_time' => ['EXP', 'IS NULL'],
                        't2.delete_time' => ['EXP', 'IS NULL'],*/
                    ])
                    ->order('t1.id desc')
                    ->paginate(20)->toarray();
            } catch (Exception $e) {
                return $this->pass($e->getMessage());
            }
        }
        return $this->pass($data);
    }

    /**
     * 收藏商品
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addFavourite()
    {
        $uid = $this->member_relang['id'];

        $goods_id = input('goods_id/d');

        // 开始验证
        $validate = new Validate([
            ['goods_id', 'number|>:0', '商品有误|商品有误'],
        ]);

        $data = [
            'goods_id' => $goods_id,
        ];

        if (!$validate->check($data)) {
            return $this->miss($validate->getError());
        } else {
            $data = $this->db->name('mall_goods')->where(['id' => $goods_id])->find();

            if (!$data) return $this->miss('商品不存在');
            if ($data['is_hidden']) return $this->miss('商品已下架');

            $result = $this->db->name('mall_goods_favourite')->where([
                'user_id' => $uid,
                'goods_id' => $goods_id,
                //'delete_time' => ['EXP', 'IS NULL']
            ])->find();

            if ($result) {
                return $this->miss('已在收藏列表');
            } else {
                $current_time = time();
                // 启动事务
                Db::startTrans();
                try {
                    // 收藏表记录
                    $this->db->name('mall_goods_favourite')->insert([
                        'user_id' => $uid,
                        'goods_id' => $goods_id,
                        'create_time' => $current_time,
                        'update_time' => $current_time,
                    ]);
                    // 收藏量+1
                    $this->db->name('mall_goods')->where('id', $goods_id)->setInc('favourite_num');
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->miss($e->getMessage());
                }

                return $this->pass('收藏成功');
            }
        }
    }

    /**
     * 删除商品收藏
     * @return \think\response\Json
     */
    public function delFavourite()
    {
        $uid = $this->member_relang['id'];

        // 全局安全过滤
        //Request::instance()->filter(['strip_tags', 'htmlspecialchars_decode', 'trim']);

        $list = input('good_ids');

        if (!$list) return $this->miss('商品选择出错');

        $goods_list = $this->db->name('mall_goods_favourite')->where(['goods_id' => ['in', $list], 'user_id' => $uid])->column('id,goods_id');
        if (sizeof($goods_list) == 0) {
            return $this->miss('取消收藏失败');
        }
        // 启动事务
        Db::startTrans();
        try {
            $this->db->name('mall_goods_favourite')->where(['id' => ['in', array_keys($goods_list)]])->delete();
            // 收藏量-1
            $this->db->name('mall_goods')->where(['id' => ['in', array_values($goods_list)]])->setDec('favourite_num');
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->miss($e->getMessage());
        }

        return $this->pass('已取消收藏');
    }

    /**
     * 添加购物车
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addCart()
    {
        $uid = $this->member_relang['id'];

        $goods_id = input('goods_id/d');
        $num = input('num/d',1);
        $sku = input('sku','');

        // 开始验证
        $validate = new Validate([
            ['goods_id', 'number|>:0', '商品有误|商品有误'],
            ['num', 'number|>:0', '数量有误|数量有误'],
        ]);

        $data = [
            'goods_id' => $goods_id,
            'num' => $num,
        ];

        if (!$validate->check($data)) {
            return $this->miss($validate->getError());
        } else {
            $data = $this->db->name('mall_goods')->where(['id' => $goods_id])->find();

            if (!$data) return $this->miss('商品不存在');
            if ($data['is_hidden']) return $this->miss('商品已下架');
            if ($data['sku']) {
                if (!$sku) {
                    return $this->miss('请选择规格');
                }
                if (!in_array($sku, explode(',', $data['sku']))) {
                    return $this->miss('规格选择错误');
                }
            }

            $result = $this->db->name('mall_goods_cart')->where(['user_id' => $uid, 'goods_id' => $goods_id, 'sku' => $sku])->find();

            $current_time = time();
            try {
                if ($result) {
                    $this->db->name('mall_goods_cart')->where('id', $result['id'])->setInc('num', $num);
                } else {
                    $this->db->name('mall_goods_cart')->insert([
                        'user_id' => $uid,
                        'goods_id' => $goods_id,
                        'merchant_id' => $data['user_id'], // 店家id
                        'num' => $num,
                        'sku' => $sku,
                        'create_time' => $current_time,
                        'update_time' => $current_time,
                    ]);
                }
            } catch (Exception $e) {
                return $this->miss($e->getMessage());
            }

            return $this->pass('添加购物车成功');
        }
    }

    /**
     * 删除购物车商品
     * @return \think\response\Json
     */
    public function delCart()
    {
        $uid = $this->member_relang['id'];

        $list = input('ids');


        if (!$list) return $this->miss('请选择商品');

        try {
            $this->db->name('mall_goods_cart')->where(['id' => ['in', $list], 'user_id' => $uid])->delete();
        } catch (Exception $e) {
            return $this->miss($e->getMessage());
        }

        return $this->pass('删除成功');
    }

    /**
     * 更改购物车商品数量
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cartChangeNum()
    {
        $uid = $this->member_relang['id'];

        $cart_id = input('cart_id/d');
        $num = input('num/d') ? input('num/d') : 1;

        // 开始验证
        $validate = new Validate([
            ['cart_id', 'number|>:0', '商品有误|商品有误'],
            ['num', 'number|>:0', '数量有误|数量有误'],
        ]);

        $data = [
            'cart_id' => $cart_id,
            'num' => $num,
        ];

        if (!$validate->check($data)) {
            exit(json_encode(['err' => $validate->getError()]));
        } else {
            $data = $this->db->name('mall_goods_cart')->where(['id' => $cart_id, 'user_id' => $uid])->find();

            if (!$data) {
                return json(['err' => '购物车商品不存在']);
            } else {
                try {
                    if ($num <= 0) {
                        //$this->db->name('mall_goods_cart')->where('id', $cart_id)->setField('delete_time', time());
                        $this->db->name('mall_goods_cart')->where('id', $cart_id)->delete();
                    } else {
                        // 对比库存
                        $stock = $this->db->name('mall_goods')->where('id', $data['goods_id'])->value('stock');
                        if ($stock < $num) return json(['err' => '数量超出范围']);

                        $this->db->name('mall_goods_cart')->where('id', $cart_id)->setField('num', $num);
                    }
                } catch (Exception $e) {
                    return json(['err' => $e->getMessage()]);
                }
                return json(['ret' => '更改成功']);
            }
        }
    }

    /**
     * 购物车列表
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function cart()
    {
        $uid = $this->member_relang['id'];

        $page = input('page/d') ? input('page/d') : 1;

        // 开始验证
        $validate = new Validate([
            ['page', 'number|>:0', '分页有误|分页有误'],
        ]);

        $data = [
            'page' => $page,
        ];

        if (!$validate->check($data)) {
            return $this->miss($validate->getError());
        } else {
            try {
                $data = $this->db->name('mall_goods_cart t1')
                    ->field("t1.id, t1.num, t1.sku, t1.create_time, t2.id goods_id, t2.image, t2.name, t2.price, t2.stock, t2.sku skus, t2.sku_price, t2.sku_stock")
                    ->join('mall_goods t2', 't2.id = t1.goods_id')
                    ->where([
                        't1.user_id' => $uid,
                        't2.is_hidden' => 0
                        /*'t1.delete_time' => ['EXP', 'IS NULL'],
                        't2.delete_time' => ['EXP', 'IS NULL'],*/
                    ])
                    ->order('t1.id desc')
                    ->page($page)
                    ->limit(10)->select();
            } catch (Exception $e) {
                return $this->miss($e->getMessage());
            }
            foreach ($data as &$v) {
                if ($v['sku']) {
                    $skus = explode(',', $v['skus']);
                    $idx = array_search($v['sku'], $skus);
                    if ($idx === false) {
                        return $this->miss('部分商品失效');
                    }
                    $sku_price = explode(',', $v['sku_price']);
                    $sku_stock = explode(',', $v['sku_stock']);
                    $v['price'] = $sku_price[$idx];
                    $v['stock'] = $sku_stock[$idx];
                }
            }
            return $this->pass($data);
        }
    }

    /**
     * 我的订单列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderList()
    {
        $uid = $this->member_relang['id'];

        // $uid = input('uid');
        $id = input('id');

        // 0待付款,1待发货,2待收货, 3已签收
        $status = input('status');
        $page = input('page/d', 1);

        // 开始验证
        $validate = new Validate([
            ['status', 'in:0,1,2,3', '订单类型有误'],
            ['page', '>:0', '分页有误'],
        ]);

        $data = [
            'status' => $status,
            'page' => $page,
        ];

        if (!$validate->check($data)) {
            exit(json_encode(['err' => $validate->getError()], JSON_UNESCAPED_UNICODE));
        } else {
            // 处理过期订单
            $this->db->name('mall_order')->where(['status' => 0, 'expire_time' => ['elt', time()]])->setField('status', -3);
            
            if ($id) {
                $where['id'] = $id;
            } else {
                $where = ['uid' => $uid];
            }
            if ($status || $status === '0') {
                $where['status'] = $status;
            }

            $data = $this->db->name('mall_order')
                ->field('id, number, money')
                ->where($where)
                ->order('id desc')
                ->paginate(10)->toarray();

            try {
                foreach ($data['data'] as $k => $v) {
                    $list = $this->db->name('mall_order_item t1')
                        ->field('t1.goods_id, t1.num, t1.price, t2.name,t2.image,t1.sku')
                        ->join('mall_goods t2', 't2.id = t1.goods_id')
                        ->order('t1.id desc')
                        ->cache(true)
                        ->where('t1.order_id', $v['id'])->select();

                    foreach ($list as $m => $n) {
                        $list[$m]['image'] = $n['image'];
                    }
                    $data['data'][$k]['list'] = $list;
                }
            } catch (Exception $e) {
                return json(['err' => $e->getMessage()]);
            }

            return json(['ret' => $data]);
        }
    }

    /**
     * 订单操作
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeOrder($w2 = 0)
    {
        $uid = $this->member_relang['id'];

        // $uid = input('uid');

        $order_id = input('order_id/d', 0);
        $type = input('type/d', 1);
        $gateway = input('gateway/d', 1);

        // 开始验证
        $validate = new Validate([
            ['order_id', 'require|>:0', '订单有误|订单有误'],
            ['type', 'in:0,1', '操作有误'],
            ['gateway', 'in:1,2'],
        ]);

        $data = [
            'order_id' => $order_id,
            'type' => $type,
        ];

        if (!$validate->check($data)) {
            exit(json_encode(['err' => $validate->getError()]));
        } else {
            // 处理过期订单
            // Db::name('mall_order')->where(['status' => 0, 'expire_time' => ['elt', time()]])->setField('status', -3);

            if ($type) {
                $order = $this->db->name('mall_order')->master()->where(['id' => $order_id])->find();
            } else {
                $order = $this->db->name('mall_order')->master()->where(['id' => $order_id, 'uid' => $uid])->find();
            }
            if (!$order) return json(['err' => '订单不存在']);

            switch ($order['status']) {
                case 0: // 待支付
                    // 启动事务
                    Db::startTrans();
                    try {
                        if ($type) { // 订单支付
                            $pays = ['api/alipay/tradeAppPay', 'api/wechat/app'];
                            $paymethods = $pays[$gateway - 1];
                            if ($w2 && $paymethods == 'api/wechat/app') {
                                $paymethods = 'api/wechat2/app';
                            }
                            $update = [];
                            if ($order['paymethod'] != $gateway) {
                                $update = ['paymethod' => $gateway, ];
                                $order['paymethod'] = $gateway;
                            }
                            if ($order['to_user']!=$uid) {
                                $update['to_user'] = $uid;
                            }
                            if (sizeof($update)) {
                                $this->db->name('mall_order')->where(['id' => $order_id])->update($update);
                            }
                            if (input('h5', 0)) {
                                $order['url'] = 'api/wap/pay';
                                $order['order_sn'] = $order['number'];
                            } else {
                                $orders = action($paymethods, ['order_sn' => $order['number'], 'total_amount' => number_format($order['money'],2), 'returnJson'=>false, 'uid'=>$uid]);
                                $order['url'] = $orders;
                            }
                        } else { // 取消订单
                            $orderitem = $this->db->name('mall_order_item')->where(['order_id' => $order_id])->select();

                            $this->db->name('mall_order')->where('id', $order['id'])->setField('status', -2);
                            if ($order['des_score'] > 0) {
                                YaoqingRecords::index($this->member['id'], 0, $order['des_score'], '订单取消退回 no.' . $order['number'], 1, '', 0);
                            }
                            if ($order['des_volley'] > 0) {
                                Balance::index($this->member['id'], $order['des_volley'], '订单取消退回 no.' . $order['number'], 1);
                            }
                            foreach ($orderitem as $k => $v) {
                                // 商品数量归还
                                $this->db->name('mall_goods')->where('id', $v['goods_id'])->update(['stock' => Db::raw('stock+'. $v['num']), 'is_hidden' => 0]);
                            }
                        }

                        // 提交事务
                        Db::commit();
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        return json(['err' => $e->getMessage()]);
                    }
                    return $type ? $this->pass($order) : json(['ret' => '操作成功']);
                case 2: // 已发货
                    // 启动事务
                    Db::startTrans();
                    try {
                        if ($type) { // 确认收货
                            $this->db->name('mall_order')->where('id', $order_id)->update(['status' => 3, 'receipt_time' => time()]);
                            // $fencheng_content = '购物商品结算';
                            // $rate = 5;
                            // User::fencheng($order['uid'], 0, $order['total'] * $rate, 'mall', $fencheng_content);
                            MallDistribution::setStatus($order['id'], 1);
                            MallOrderFanli::setStatus($order['id'], 1);
                        }

                        // 提交事务
                        Db::commit();
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        return json(['err' => $e->getMessage()]);
                    }
                    return json(['ret' => '操作成功']);
                default:
                    if ($type == 1) return json(['err'=>'订单失效或已支付']);
                    return json(['err' => '操作有误']);
            }
        }
    }

    /**
     * 收货地址列表
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function addressList()
    {
        $uid = $this->member_relang['id'];

        // $uid = input('uid');

        $page = input('page/d') ? input('page/d') : 1;

        // 开始验证
        $validate = new Validate([
            ['page', 'number|>:0', '分页有误|分页有误'],
        ]);

        $data = [
            'page' => $page,
        ];

        if (!$validate->check($data)) {
            exit(json_encode(['err' => $validate->getError()]));
        } else {
            try {
                $data = $this->db->name('mall_member_address')
                    ->field('id, uid, receiver, mobile, area, address, is_default')
                    ->where(['uid' => $uid])
                    ->order('is_default desc, id desc')
                    ->paginate(10)->toarray();
            } catch (Exception $e) {
                return json(['err' => $e->getMessage()]);
            }
        }

        return json(['ret' => $data]);

    }

    /**
     * 删除收货地址
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delAddress()
    {
        $uid = $this->member_relang['id'];

        // $uid = input('uid');

        $address_id = input('id/d');

        // 开始验证
        $validate = new Validate([
            ['address_id', '>:0', '收货地址有误'],
        ]);

        $data = [
            'address_id' => $address_id,
        ];

        if (!$validate->check($data)) {
            exit(json_encode(['err' => $validate->getError()]));
        } else {
            $data = $this->db->name('mall_member_address')->where(['id' => $address_id, 'uid' => $uid])->find();

            if (!$data) return json(['err' => '地址不存在']);

            $count = $this->db->name('mall_member_address')->where(['uid' => $uid])->count();

            if ($count >= 2 && $data['is_default']) return json(['err' => '不能删除默认地址']);

            try {
                //$this->db->name('mall_member_address')->where('id', $address_id)->setField('delete_time', time());
                $this->db->name('mall_member_address')->where('id', $address_id)->delete();
            } catch (Exception $e) {
                return json(['err' => $e->getMessage()]);
            }
            return json(['ret' => '删除成功']);
        }
    }

    /**
     * 添加/修改收货地址
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateAddress()
    {
        $uid = $this->member_relang['id'];

        // $uid = input('uid');

        // 开始验证
        $validate = new Validate([
            ['id', '>:0', '收货地址选择有误'],
            ['receiver', 'require|chsAlpha|length:1,50', '收货人不能为空|收货人名称只能字母和汉字|收货人名称在1-50字符之间'],
            ['mobile', 'require', '手机不能为空'],
            ['area', 'require', '地区不能为空'],
            ['address', 'require', '详细地址不能为空'],
        ]);

        $data = [
            'id' => $address_id = input('id/d'),
            'receiver' => $receiver = input('receiver'),
            'mobile' => $mobile = input('mobile'),
            'area' => $area = input('area'),
            'address' => $address = input('address'),
            'is_default' => $is_default = input('is_default/d') ? input('is_default/d') : 0,
        ];

        if (!$validate->check($data)) {
            exit(json_encode(['err' => $validate->getError()]));
        } else {
            if ($address_id) {
                $result = $this->db->name('mall_member_address')->where([
                    'id' => $address_id,
                    'uid' => $uid,
                    //'delete_time' => ['EXP', 'IS NULL']
                ])->find();

                if (!$result) return json(['err' => '收货地址选择有误']);

                $data['update_time'] = time();

                // 启动事务
                Db::startTrans();
                try {
                    if ($data['is_default']) {
                        $this->db->name('mall_member_address')->where(['uid' => $uid])->setField('is_default', 0);
                    }

                    $this->db->name('mall_member_address')->where('id', $address_id)->update($data);
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['err' => $e->getMessage()]);
                }
                return json(['ret' => '修改成功']);
            } else {
                $count = $this->db->name('mall_member_address')->where(['uid' => $uid])->count();
                if (!$count) {
                    $data['is_default'] = 1;
                }
                $result = $this->db->name('mall_member_address')->where(['uid' => $uid, 'is_default' => 1])->find();

                $current_time = time();
                // 启动事务
                Db::startTrans();
                try {
                    $data['uid'] = $uid;
                    $data['create_time'] = $current_time;
                    $data['update_time'] = $current_time;
                    unset($data['id']);

                    $this->db->name('mall_member_address')->insert($data);

                    if ($result && $is_default) {
                        $this->db->name('mall_member_address')->where('id', $result['id'])->setField('is_default', 0);
                    }

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json(['err' => $e->getMessage()]);
                }

                return json(['ret' => '添加成功']);
            }
        }
    }
}